package com.wzdigit.wms.wms.service.core;

import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicParamApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.mes.basic.dto.ParamDetailDTO;
import com.wzdigit.wms.basic.domain.dtos.oqc.OqcInspDtlDto;
import com.wzdigit.wms.basic.mapper.core.oqc.OqcInspDtlMapper;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 
 * 翻拍-判检执行【执行入口】
 * @author Administrator
 *
 */
@Service
@Slf4j
public class OqcNewTaskService {

	@Autowired
    private OqcHeaderNewTaskService oqcHeaderNewTaskService;
	
    @Autowired
    private OqcInspDtlMapper oqcInspDtlMapper;

	@Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
	private BasicDataItemDetailApi dataItemDetailApi;
    
    @Reference(version = "${dubbo.providers.basic.BasicParam.api:1.0.0}", check = false)
    private BasicParamApi basicParamApi;

    //private final Lock lock = new ReentrantLock();
    
	/**
	 * 判检任务执行
	 */
	public void execute() {
		DataItemDetailDTO dto = dataItemDetailApi.getDataItemDetailByPCodeAndName("oqc_fp_flag", "key");
		if (dto!=null){
			if ("0".equals(dto.getItemValue())){
				return;
			}
		}
		execute(null);
    }




	/**
	 * 判检任务执行
	 * 
	 * @param inspNo
	 */
	public synchronized void execute(String inspNo) {
		//lock.lock();
		List<OqcInspDtlDto> datas = null;
		try {

			log.info("【定时任务-产品判检】执行开始");
			try {
				 datas = oqcInspDtlMapper.selectOqcTaskData(inspNo);
				 //Shift.fatal("/////");
			}catch (Exception e){
				log.info("查询异常selectOqcTaskData");
				e.printStackTrace();
			}

			log.info("【定时任务-产品判检】执行，数量：{}", datas.size());
	        if (CollectionUtil.isEmpty(datas)) {
	            return;
	        }
	        // 是否需要回传sap标识
	        boolean isCallSAPInterface = isCallSAPInterface();
	        
	        // 根据送检单主档ID分组
	        Map<Integer, List<OqcInspDtlDto>> oqcInspMap = datas.stream().collect(Collectors.groupingBy(g -> g.getOqcInspId()));

	        // 遍历送检单主档start
	        for (Integer oqcInspId : oqcInspMap.keySet()) {
	        	try {
	        		datas = oqcInspMap.get(oqcInspId);
	        		oqcHeaderNewTaskService.execute(oqcInspId, datas, isCallSAPInterface);
	        		log.info("【定时任务-产品判检】主档执行成功：{}，数量：{}", oqcInspId, datas.size());
				} catch (Exception e) {
					log.error("【定时任务-产品判检】主档执行异常/失败：{}，数量：{}", oqcInspId, datas.size());
					e.printStackTrace();
				}
			} // 遍历送检单主档完毕end
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//lock.unlock();
		}
    }
	
    /**
     * 获取系统参数，是否开启调用SAP报检接口
     * 
     * @return
     */
    private boolean isCallSAPInterface() {
        ParamDetailDTO data = basicParamApi.getByCode("Is_callSAPInterface");
        if (data != null && data.getSystemParamValue() != null) {
            return "true".equals(data.getSystemParamValue());
        }
        return true;
    }
}
